package xtu.www.common.router;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;

import java.util.Set;
import java.util.TreeMap;

import xtu.www.common.router.rule.ActivityRule;
import xtu.www.common.router.rule.Rule;

/**
 * Created by huilin on 2017/6/15.
 */

public class RouterInternal {
    private TreeMap<String, Rule> mRuleMap;

    private RouterInternal() {
        mRuleMap = new TreeMap<>();
        //初始化默认的路由
        mRuleMap.put(ActivityRule.ACTIVITY_SCHEME, new ActivityRule());
    }

    private static class RouterInternalHolder {
        private static RouterInternal INSTANCT = new RouterInternal();
    }

    public static RouterInternal getIns() {
        return RouterInternalHolder.INSTANCT;
    }

    public void addRule(@NonNull String scheme, @NonNull Rule rule) {
        mRuleMap.put(scheme, rule);
    }

    private Rule getRule(String pattern) {
        Set<String> stringSet = mRuleMap.keySet();
        for (String scheme : stringSet) {
            if (pattern.startsWith(scheme)) {
                return mRuleMap.get(scheme);
            }
        }
        return null;
    }


    public RouterInternal router(@NonNull String pattern, @NonNull Class aClass) {
        Rule rule = getRule(pattern);
        if (rule == null) {
            throw new IllegalArgumentException("no find scheme");
        }
        rule.router(pattern, aClass);
        return this;
    }

    public Intent invoke(Context context, String pattern) {
        Rule rule = getRule(pattern);
        if (rule == null) {
            throw new IllegalArgumentException("no find scheme");
        }
        return (Intent) rule.invoke(context, pattern);
    }
}
